Summary
attributes, attr, class, methods, UseMethod, getAnywhere
attributes Print attributes of an object. attr change attributes of an object. class change class of an object. methods Print methods in a generic function. UseMethod Constructing a generic function. GF <- function(x, ...) UseMethod('GF') getAnywhere find a function
Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #------------- Create a generic method > whoami <- function (x, ...) UseMethod ( "whoami" ) > whoami.foo <- function (x) print ( "I am a foo" ) > whoami.bar <- function (x) print ( "I am a bar" ) > whoami.default <- function (x) print ( "I don't know who I am" ) > a = 1:10 > b = 2:20 > whoami (a) # No class assigned [1] "I don't know who I am" > attr (a, 'class' ) <- 'foo' > attr (b, 'class' ) <- c ( 'baz' , 'bam' , 'bar' ) > whoami (a) [1] "I am a foo" > whoami (b) # Search MRO for defined method [1] "I am a bar" > attr (a, 'class' ) <- 'bar' # Change the class of 'a' > whoami (a) [1] "I am a bar" |
Golden rule
- eveything is an object, a vector
- DO NOT call methods directly, instead use a generic function, which dispatches methods to objects according to their classes.
Concepts
-
Inheritance: A way to form new classes using classes that have already been defined.
class(x) = c('newClass', class(x))
References
http://www.ibm.com/developerworks/linux/library/l-r3/index.html#N10139 http://brainimaging.waisman.wisc.edu/~perlman/R/A1%20Introduction%20to%20object-oriented%20programming.pdf
Hide Comments